<template>
  <CustomNavBar title="小区搜索" />
  <view class="search-page">
    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <image class="search-icon" src="/static/images/activity_pile/ico_search.svg" />
        <input 
          class="search-input" 
          type="text" 
          placeholder="搜索城市/区县/地点"
          v-model="searchKeyword"
          @input="onSearchInput"
        />
        <image 
          v-if="searchKeyword" 
          class="clear-icon" 
          src="/static/images/activity_pile/ico_clear.svg"
          @click="clearSearch"
        />
      </view>
    </view>

    <!-- 搜索结果 -->
    <view v-if="showSearchResults" class="search-results">
      <view v-if="isSearching" class="loading-container">
        <text class="loading-text">搜索中...</text>
      </view>
      <view v-else-if="searchResults.length > 0" class="results-list">
        <view 
          class="result-item" 
          v-for="(item, index) in searchResults" 
          :key="index"
          @click="selectSearchResult(item)"
        >
          <view class="result-left">
            <image class="location-icon" src="/static/images/mini-local.png" />
            <view class="result-info">
              <text class="result-name">
                <text 
                  v-for="(part, partIndex) in getHighlightedName(item.name)" 
                  :key="partIndex"
                  :class="{ 'highlight-text': part.highlight }"
                >{{ part.text }}</text>
              </text>
              <text class="result-address">{{ item.distance }} {{ item.address }}</text>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="no-results">
        <text class="no-results-text">暂无搜索结果</text>
      </view>
    </view>

    <!-- 当前位置和历史搜索 - 仅在非搜索状态显示 -->
    <view v-if="!showSearchResults">
      <!-- 当前位置 -->
      <view class="current-location">
        <text>当前：</text>
        <text>{{ currentCommunity }}</text>
      </view>

      <!-- 搜索历史 -->
      <view class="search-history">
        <view class="history-header">
          <text class="history-title">历史搜索</text>
        </view>
        <view class="history-list">
          <view 
            class="history-item" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @click="selectHistoryItem(item)"
          >
            <text class="history-text">{{ item.name }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomNavBar from '@/components/CustomNavBar.vue';
import PileApi from '@/api/pile/pile.js';
import { bd09togcj02 } from '@/utils/coordinate.js';

// 响应式数据
const searchKeyword = ref('');
const currentCommunity = ref('');
const currentLatitude = ref(0);
const currentLongitude = ref(0);
const searchResults = ref([]);
const isSearching = ref(false);
const showSearchResults = ref(false);

// 搜索历史数据
const searchHistory = ref([
//   // { name: '国通意义－B座', latitude: 31.8206, longitude: 117.2272 },
//   // { name: '合肥XX品牌公司', latitude: 31.8306, longitude: 117.2372 },
//   // { name: '国通意义－B座', latitude: 31.8406, longitude: 117.2472 },
//   // { name: '合肥XX品牌公司', latitude: 31.8506, longitude: 117.2572 }
]);

// 防抖定时器
let searchTimer = null;

// 搜索API调用
const searchCommunities = async (keyword) => {
  if (!keyword.trim()) {
    searchResults.value = [];
    showSearchResults.value = false;
    return;
  }
  
  isSearching.value = true;
  showSearchResults.value = true;
  
  try {
    // 调用API接口
    const response = await PileApi.searchPlot(
      keyword,
      currentLongitude.value,
      currentLatitude.value
    );
    
    if (response && response.length > 0) {
      // 转换API返回的数据格式
      const formattedData = response.map(item => {
        return {
          name: item.name,
          distance: '', // API未返回距离信息，可以根据经纬度计算或留空
          address: `${item.district}-${item.address}`,
          // latitude: item.latitude,
          // longitude: item.longitude,
          latitude: parseFloat(item.lat),
          longitude: parseFloat(item.lon)
        };
      });
      
      searchResults.value = formattedData;
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error('搜索失败:', error);
    searchResults.value = [];
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    isSearching.value = false;
  }
};

// 防抖搜索
const debounceSearch = (keyword) => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  
  searchTimer = setTimeout(() => {
    searchCommunities(keyword);
  }, 300);
};

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  debounceSearch(newValue);
});

// 方法定义
const onSearchInput = () => {
  // 搜索输入处理逻辑已通过watch实现
  console.log('搜索关键词:', searchKeyword.value);
};

const clearSearch = () => {
  searchKeyword.value = '';
  searchResults.value = [];
  showSearchResults.value = false;
};

const selectSearchResult = (item) => {
  console.log('选中搜索结果:', item);
  console.log('选中搜索结果的经纬度(BD09):', item.longitude, item.latitude);
  // 将BD09坐标转换为GCJ02坐标
  const [convertedLng, convertedLat] = bd09togcj02(item.longitude, item.latitude);
  console.log('转换后的经纬度(GCJ02):', convertedLng, convertedLat);
  // 创建转换后的数据对象
  const convertedItem = {
    name: item.name,
    latitude: convertedLat,
    longitude: convertedLng
  };
  
  // 保存到搜索历史
  saveToHistory(convertedItem);
  
  // 返回选中的数据到上一页面
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2];
  
  if (prevPage && prevPage.$vm) {
    // 检查函数是否存在
    if (typeof prevPage.$vm.updateLocationFromSearch === 'function') {
      prevPage.$vm.updateLocationFromSearch({
        community: convertedItem.name,
        latitude: convertedItem.latitude,
        longitude: convertedItem.longitude
      });
    } else {
      console.error('updateLocationFromSearch函数不存在');
      uni.showToast({
        title: '页面通信失败',
        icon: 'none'
      });
    }
  }
  
  uni.navigateBack();
};

const selectHistoryItem = (item) => {
  // 选择历史搜索项，不需要重复保存到历史
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2];
  
  if (prevPage && prevPage.$vm) {
    // 检查函数是否存在
    if (typeof prevPage.$vm.updateLocationFromSearch === 'function') {
      //转化坐标系
      // const [convertedLng, convertedLat] = bd09togcj02(item.longitude, item.latitude);
      prevPage.$vm.updateLocationFromSearch({
        community: item.name,
        latitude: item.latitude,
        longitude: item.longitude
      });
    } else {
      console.error('updateLocationFromSearch函数不存在');
      uni.showToast({
        title: '页面通信失败',
        icon: 'none'
      });
    }
  }
  
  uni.navigateBack();
};

// 获取高亮显示的名称
const getHighlightedName = (name) => {
  if (!searchKeyword.value || !name) {
    return [{ text: name, highlight: false }];
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  const lowerName = name.toLowerCase();
  const parts = [];
  let lastIndex = 0;
  
  let index = lowerName.indexOf(keyword);
  while (index !== -1) {
    // 添加匹配前的文本
    if (index > lastIndex) {
      parts.push({
        text: name.substring(lastIndex, index),
        highlight: false
      });
    }
    
    // 添加匹配的文本
    parts.push({
      text: name.substring(index, index + keyword.length),
      highlight: true
    });
    
    lastIndex = index + keyword.length;
    index = lowerName.indexOf(keyword, lastIndex);
  }
  
  // 添加剩余的文本
  if (lastIndex < name.length) {
    parts.push({
      text: name.substring(lastIndex),
      highlight: false
    });
  }
  
  return parts;
};

// 保存到搜索历史
const saveToHistory = (item) => {
  // 检查是否已存在相同项目
  console.log('saveToHistory: ', item);
  const existingIndex = searchHistory.value.findIndex(historyItem => 
    historyItem.name === item.name && 
    historyItem.latitude === item.latitude && 
    historyItem.longitude === item.longitude
  );
  
  if (existingIndex !== -1) {
    // 如果已存在，移除旧的
    searchHistory.value.splice(existingIndex, 1);
  }
  
  // 添加到历史记录开头
  searchHistory.value.unshift({
    name: item.name,
    latitude: item.latitude,
    longitude: item.longitude
  });
  
  // 限制历史记录数量，最多保留10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10);
  }
  
  // 保存到本地存储
  try {
    uni.setStorageSync('search_history', searchHistory.value);
  } catch (error) {
    console.error('保存搜索历史失败:', error);
  }
};

// 从本地存储加载搜索历史
const loadSearchHistory = () => {
  try {
    const savedHistory = uni.getStorageSync('search_history');
    if (savedHistory && Array.isArray(savedHistory)) {
      searchHistory.value = savedHistory;
    }
  } catch (error) {
    console.error('加载搜索历史失败:', error);
  }
};

// 页面加载时接收参数
onLoad((options) => {
  // 加载搜索历史
  loadSearchHistory();
  
  if (options.community) {
    currentCommunity.value = decodeURIComponent(options.community);
  }
  if (options.latitude) {
    currentLatitude.value = parseFloat(options.latitude);
  }
  if (options.longitude) {
    currentLongitude.value = parseFloat(options.longitude);
  }
  
  console.log('接收到的参数:', {
    community: currentCommunity.value,
    latitude: currentLatitude.value,
    longitude: currentLongitude.value
  });
});
</script>

<style scoped>
.search-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 0;
}

.search-container {
  background-color: #ffffff;
  padding: 12px 16px;
  /* border-bottom: 1px solid #f0f0f0; */
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 20px;
  padding: 8px 12px;
  height: 36px;
}

.search-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  font-size: 14px;
  background-color: transparent;
  border: none;
  outline: none;
}

.search-input::placeholder {
  color: #999999;
}

.clear-icon {
  width: 16px;
  height: 16px;
  margin-left: 8px;
}

.current-location {
  background-color: #ffffff;
  padding: 16px 30rpx;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.search-history {
  background-color: #ffffff;
  margin-top: 8px;
}

.history-header {
  padding: 16px 30rpx 8px 30rpx;
  /* border-bottom: 1px solid #f0f0f0; */
}

.history-title {
  font-size: 14px;
  color: #32333F;
}

.history-list {
  padding: 0;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 0; /* 修改：移除底部margin */
  border-radius: 0; /* 修改：移除圆角 */
  position: relative; /* 添加：相对定位，用于绝对定位分割线 */
  /* padding: 12px 0; */
  /* border-bottom: 1px solid #f8f8f8; */
}
.history-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 30rpx; /* 设置左侧边距，与文字对齐 */
  right: 0;
  height: 1rpx;
  background-color: #E5E5E5;
}

.history-item:last-child {
  border-bottom: none;
}

.history-text {
  font-size: 16px;
}

/* 搜索结果样式 */
.search-results {
  background-color: #ffffff;
  margin-top: 8px;
}

.loading-container {
  padding: 40rpx;
  text-align: center;
}

.loading-text {
  font-size: 14px;
  color: #999999;
}

.results-list {
  padding: 0;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  position: relative;
}

.result-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 30rpx;
  right: 0;
  height: 1rpx;
  background-color: #E5E5E5;
}

.result-item:last-child::after {
  display: none;
}

.result-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.location-icon {
  width: 45rpx;
  height: 45rpx;
  margin-right: 10rpx;
  margin-bottom: 40rpx;
}

.result-info {
  flex: 1;
}

.result-name {
  font-size: 32rpx;
  /* display: block; */
  margin-bottom: 8rpx;
}

.highlight-text {
  color: #1BCCB4;
  font-weight: 500;
}

.result-address {
  font-size: 28rpx;
  color: #999999;
  display: block;
}

.no-results {
  padding: 40rpx;
  text-align: center;
}

.no-results-text {
  font-size: 14px;
  color: #999999;
}
</style>